﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WineStore.DAL;
using WineStore.Models;
using System.Data.Entity;
using System.Data;

namespace WineStore.Controllers
{
    public class ShoppingCartController : Controller
    {
        WineDbContext storeDB = new WineDbContext();
       
        //
        // GET: /ShoppingCart/
        public ActionResult Index()
        {
            SetCookie();
            var cart = ShoppingCart.GetCart(this.HttpContext);

            // Set up our ViewModel
            var viewModel = new ShoppingCartViewModel
            {
                CartItems = cart.GetCartItems(),
                CartTotal = cart.GetTotal()
            };

            ViewBag.Logo = null;
            ViewBag.Categories = null;

            using (var db = new WineDbContext())
            {
                ViewBag.Logo = db.Logo.ToList();
                ViewBag.Categories = db.Categories.ToList();
            }

            ViewBag.TotalCartItems = cart.TotalCartItems();
            // Return the view
            return View(viewModel);
        }

        public ActionResult ViewCart()
        {
            SetCookie();
            var cart = ShoppingCart.GetCart(this.HttpContext);

            // Set up our ViewModel
            var viewModel = new ShoppingCartViewModel
            {
                CartItems = cart.GetCartItems(),
                CartTotal = cart.GetTotal()
            };
            // Return the view
            return View(viewModel);
        }


        // Empty Cart
        [HttpPost]
        public ActionResult EmptyCart()
        {
            SetCookie();
            var cart = ShoppingCart.GetCart(this.HttpContext);
            cart.EmptyCart();
            var results = new ShoppingCartRemoveViewModel
            {
                Message = " Your carts has been removed!",
                TotalCartItems = cart.TotalCartItems()
            };
            return Json(results);
        }

        //
        // GET: /Store/AddToCart/5
        public ActionResult AddToCart(int id)
        {
            SetCookie();
            // Retrieve the album from the database
            var addedProduct = storeDB.Products
                .Single(product => product.ProductId == id);

            // Add it to the shopping cart
            var cart = ShoppingCart.GetCart(this.HttpContext);

            cart.AddToCart(addedProduct);

            // Go back to the main store page for more shopping
            return RedirectToAction("Index", "ShoppingCart");
        }
        //
        // AJAX: /ShoppingCart/RemoveFromCart/5
        [HttpPost]
        public ActionResult RemoveFromCart(int id)
        {
            SetCookie();
            // Remove the item from the cart 
            var cart = ShoppingCart.GetCart(this.HttpContext);

            // Get the name of the album to display confirmation 
            string productName = storeDB.Carts
                .Single(item => item.RecordId == id).Product.ProductName_EN;

            // Remove from cart 
            int itemCount = cart.RemoveFromCart(id);

            // Display the confirmation message 
            var results = new ShoppingCartRemoveViewModel
            {
                Message = Server.HtmlEncode(productName) +
                    " has been removed from your shopping cart.",
                TotalCartItems = cart.TotalCartItems(),
                CartTotal = cart.GetTotal(),
                CartCount = cart.GetCount(),
                ItemCount = itemCount,
                DeleteId = id
            };
            return Json(results);
        }

        [HttpPost]
        public ActionResult UpdateCartCount(int id, int cartCount)
        {
            SetCookie();
            ShoppingCartRemoveViewModel results = null;
            try
            {
                // Get the cart 
                var cart = ShoppingCart.GetCart(this.HttpContext);

                // Get the name of the album to display confirmation 
                string productName = storeDB.Carts
                    .Single(item => item.RecordId == id).Product.ProductName_EN;
                // Get TotalPrice
                decimal totalPrice = cart.GetTotalPrice(id, cartCount);

                // Update the cart count 
                int itemCount = cart.UpdateCartCount(id, cartCount);

                //Prepare messages
                string msg = "The quantity of " + Server.HtmlEncode(productName) +
                        " has been update in your shopping cart.";
                if (itemCount == 0) msg = Server.HtmlEncode(productName) +
                        " has been removed from your shopping cart.";
                //
                // Display the confirmation message 
                results = new ShoppingCartRemoveViewModel
                {
                    Message = msg,
                    TotalCartItems = cart.TotalCartItems(),
                    TotalPrice = totalPrice,
                    CartTotal = cart.GetTotal(),
                    CartCount = cart.GetCount(),
                    ItemCount = itemCount,
                    DeleteId = id
                };
            }
            catch
            {
                results = new ShoppingCartRemoveViewModel
                {
                    Message = "Quantity must be in distance from 1 đến 100.000",
                    CartTotal = -1,
                    CartCount = -1,
                    ItemCount = -1,
                    DeleteId = id
                };
            }
            return Json(results);
        }

        //
        // GET: /ShoppingCart/CartSummary
        [ChildActionOnly]
        public ActionResult CartSummary()
        {
            SetCookie();
            var cart = ShoppingCart.GetCart(this.HttpContext);

            ViewData["CartCount"] = cart.GetCount();
            return PartialView("CartSummary");
        }

        // GET: /Home/ChangeCulture/
        public ActionResult ChangeCulture(string lang, string returnUrl)
        {
            SetCookie();
            HttpCookie cookies = Request.Cookies.Get("language");
            if (cookies == null)
            {
                cookies = new HttpCookie("language");
                cookies.Value = lang;
            }
            else
            {
                cookies.Value = lang;
            }
            cookies.Expires = DateTime.Now.AddDays(30);
            Response.Cookies.Add(cookies);
            return Redirect(returnUrl);
        }

        // SetCookie
        private void SetCookie()
        {
            HttpCookie cookie = Request.Cookies.Get("language");
            if (cookie == null)
            {
                cookie = new HttpCookie("language");
                Response.Cookies["language"].Value = "EN";
                Response.Cookies.Add(cookie);
            }
        }
    }
}
